package com.jsServer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.entity.User;


@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {

    @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		//当前页
		int currPageNum = Integer.parseInt(req.getParameter("page.currPageNum"));
		//每页记录数 
		int pageRowSize = Integer.parseInt(req.getParameter("page.pageRowSize"));
		int firstResult = Integer.parseInt(req.getParameter("page.firstResult"));
		int maxResult = Integer.parseInt(req.getParameter("page.maxResult"));
		int totalRowSize = 0;
		PrintWriter out = resp.getWriter();
		// 准备数据(这里面可以从数据库获取)
		List<User> userList = new ArrayList<User>();
		for (int i = 0; i < 65; i++){
			User user = new User();
			user.setId(i+1);
			user.setUser("zhangsan" + (i+1));
			user.setPassword(i + "aac");
			user.setEmail("example@126.com");
			user.setAge(11);
			user.setSex('1');
			
			userList.add(user);
		}
		totalRowSize = userList.size();
		
		//封装当面需显示的数据
		List<User> showData = new ArrayList<User>();
		//当前页首位索引
		int index ;
		if (currPageNum == 1){
			index = currPageNum - 1;
		} else {
			index = pageRowSize * (currPageNum - 1);
		}
		//下一页索引
		int nextPageIndex = 0;
		if (maxResult > totalRowSize){
			nextPageIndex = (totalRowSize % maxResult);
		} else {
			nextPageIndex = maxResult;
		}
		for (; index < nextPageIndex; index++){
			User tmpUser = userList.get(index);
			
			showData.add(tmpUser);
		}
		
		//对象转成json对象
		JSONArray jsonArray = JSONArray.fromObject(showData);
		out.print(jsonArray);
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

}
